// axios基础封装
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import { ElMessage } from 'element-plus'


const httpInstance = axios.create({
    baseURL: "/api",
    timeout: 5000
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => {
    if (res.data.code === 0) {
        return res.data
    }
    //操作失败
    ElMessage.error(res.data.message ? res.data.message : '服务异常')
    return Promise.reject(res.data)
}, e => {
    const userStore = useUserStore()
    if(e.response.status === 401){
        ElMessage.warning('请先登录')
        userStore.clearUserInfo()
        router.push('/login')
    }
    return Promise.reject(e)
})


export default httpInstance